<?php
namespace app\admin\controller;

use Auth\Auth;
use think\Db;
use think\Exception;
use app\admin\controller\Common;
class User extends Common
{
    /***管理员操作****/
    //管理员列表
    function userlist(){
        /**接收数据 组合查询条件**/
        $datemin=input("datemin");
        $datemax=input("datemax");
        $username=replace_specialChar(input("username"));
        $where="1 ";
        if($datemin){
            $where.=" and addtime>=UNIX_TIMESTAMP('".$datemin."')";
        }
        if($datemax){
            $where.=" and addtime<=UNIX_TIMESTAMP('".$datemax."')";
        }
        if($username){
            $where.=" and username like '%".$username."%'";
        }
        $auth=new Auth();
        $rs=db("user")->where($where)->order("id asc")->select();
        if($rs){
            foreach ($rs as $k=>$v){
                $role=$auth->getGroups($v["id"]);
                $role_str="";
                foreach($role as $k2=>$v2){
                    $role_str.="【".$v2["title"]."】";
                }
                $rs[$k]["role"]=$role_str;
            }
        }
        $this->assign("datemin",$datemin);
        $this->assign("datemax",$datemax);
        $this->assign("username",$username);
        $this->assign("userlist",$rs);
        return view();    
    }
    
    //添加管理员
    function adduser(){
        if(request()->isAjax()){
            $res=array();
            $randstr=getRandStr();
            $data=array(
                "id"=>input("id"),
                "username"=>input("username"),
                "userpwd"=>encodePwd(input("userpwd"), $randstr),
                "pwdcode"=>$randstr,
                "tel"=>input("tel"),
                "email"=>input("email"),
                "status"=>input("status"),
                "addtime"=>time(),
            );
            Db::startTrans();
            try{
                //用户ID
                $uid=$data["id"];
                if($uid){
                    db("user")->update($data);
                }else{
                    db("user")->insert($data);
                    $uid=db("user")->getLastInsID();
                }
                //删除用户所有角色 添加新的角色
                db("auth_group_access")->where("uid=".$uid)->delete();
                $rolelist=input("role/a");
                foreach ($rolelist as $v){
                    $data=array(
                        "uid"=>$uid,
                        "group_id"=>$v
                    );
                    db("auth_group_access")->insert($data);
                }
                Db::commit();
                $res["error"]="success";
            }catch (Exception $e){
                Db::rollback();
                $res["error"]="操作失败，请重试！";
            }
            return json($res);
        }else{
            $id=input("id");
            //读取角色表
            $role=$this->myrolelist();
            if($id){
                //读取角色用户组合表
                $role_user=db("auth_group_access")->where("uid=".$id)->select();
                $roleuser=array();
                foreach ($role_user as $v){
                    $roleuser[]=$v["group_id"];
                }
                //读取该权限
                $this->assign("user",db("user")->find($id));
                $this->assign("role",$role);
                $this->assign("roleuser",$roleuser);
                return view();
            }else{
                $this->assign("role",$role);
                return view();
            }
        }
    }
    
    //管理员密码修改 强制修改
    function editpwd(){
        if(request()->isAjax()){
            $res=[];
            $randstr=getRandStr();
            $data=array(
                "userpwd"=>encodePwd(input("userpwd"), $randstr),
                "pwdcode"=>$randstr,
            );
            if(db("user")->where("id=".input("id",0))->update($data)){
                $res["error"]="success";
            }else{
                $res["error"]="操作失败";
            }
            return json($res);
        }else{
            $this->assign("id",input("id",0));
            return view();
        }
    }
    
    //删除管理员
    function deluser(){
        if(request()->isAjax()){
            $res=array();
            $id=input("id",0);
            Db::startTrans();
            try{
                db("user")->where("id=".$id)->delete();
                db("auth_group_access")->where("uid=".$id)->delete();
                $res["error"]="success";
                Db::commit();
            }catch (Exception $e){
                $res["error"]="管理员删除失败";
                Db::rollback();
            }
            return json($res);
        }
    }
    
    //删除管理员ALL
    function deluserAll(){
        if(request()->isAjax()){
            $res=array();
            $id=input("id/a");
            Db::startTrans();
            try{
                foreach ($id as $v){
                    db("user")->where("id=".$v["id"])->delete();
                    db("auth_group_access")->where("uid=".$v["id"])->delete();
                }
                $res["error"]="success";
                Db::commit();
            }catch (Exception $e){
                $res["error"]="管理员删除失败";
                Db::rollback();
            }
            return json($res);
        }
    }
    
    //批量修改管理员角色
    function userroleall(){
        if(request()->isAjax()){
            $res=array();
            $id=input("id");
            $role=input("role/a");
            $status=input("status");
            Db::startTrans();
            try{
                //删除所有用户角色
                db("auth_group_access")->where("uid in (".$id.")")->delete();
                //把所有用户变为禁用状态
                db("user")->where("id in (".$id.")")->update(["status"=>$status]);
                //新增新的角色
                $idarr=explode(",",$id);
                foreach ($idarr as $v){
                    foreach ($role as $v2){
                        $data=array(
                            "uid"=>$v,
                            "group_id"=>$v2
                        );
                        db("auth_group_access")->insert($data);
                    }
                }
                $res["error"]="success";
                Db::commit();
            }catch (Exception $e){
                $res["error"]="操作失败!";
                Db::rollback();
            }
            return json($res);
        }else{
            //读取用户ID
            $this->assign("uid",input("id"));
            //读取所有角色
            $this->assign("role",$this->myrolelist());
            return view();
        }
    }
    
    /***角色操作****/
    //角色列表
    function rolelist(){
        $rs=db("auth_group")->select();
        $this->assign("rolelist",$rs);
        return view();
    }
    
    //添加角色
    function addrole(){
        if(request()->isAjax()){
            $res=array();
            $data=array(
                "id"=>input("id"),
                "title"=>input("name"),
                "status"=>input("status"),
                "rules"=>implode(",",input("ruleid/a")),
            );
            Db::startTrans();
            try{
                //判断是新增还是修改
                if($data["id"]){
                    //修改
                    db("auth_group")->where("id=".$data["id"])->update($data);
                }else{
                    //新增
                    db("auth_group")->insert($data);
                }
                
                $res["error"]="success";
                Db::commit();
            }catch (Exception $e){
                $res["error"]="sorry 操作失败!";
                Db::rollback;
            }
            return json($res);
        }else{
            $id=input("id");
            if($id){
                //读取角色色所有权限
                $rs=db("auth_group")->field("rules")->find($id);
                $this->assign("ruleid",explode(",",$rs["rules"]));
                //返回id
                $this->assign("id",$id);
                //返回角色名称和状态
                $this->assign("role",db("auth_group")->field("title,status")->find($id));
            }
            $this->assign("permission",$this->getaccesslist());
            return view();
        }
    }
    
    //删除角色
    function delrole(){
        if(request()->isAjax()){
            $res=array();
            $id=input("id",0);
            Db::startTrans();
            try{
                db("auth_group")->where("id=".$id)->delete();
                db("auth_group_access")->where("uid=".$id)->delete();
                $res["error"]="success";
                Db::commit();
            }catch (Exception $e){
                $res["error"]="权限删除失败";
                Db::rollback();
            }
            return json($res);
        }
    }
    
    //删除角色 All
    function delroleAll(){
        if(request()->isAjax()){
            $res=array();
            $id=input("id/a");
            Db::startTrans();
            try{
                foreach ($id as $v){
                    db("auth_group")->where("id=".$v["id"])->delete();
                    db("auth_group_access")->where("group_id=".$v["id"])->delete();
                }
                $res["error"]="success";
                Db::commit();
            }catch (Exception $e){
                $res["error"]="角色删除失败";
                Db::rollback();
            }
            return json($res);
        }
    }
    
    /***权限操作****/
    //权限列表
    function permission(){
        $this->assign("permission",$this->getaccesslist());
        return view();
    }
    
    //权限列表&左侧菜单
    static function getaccesslist($menu=0){
        /*
         * $menu: 0获取权限列表    1获取左侧菜单
         * */
        $where=1;
        if($menu==1){
            $where.=" and menu=1 or (length(name)=length(replace(name,'/','')))";
        }
        $rs=db("auth_rule")->where($where)->order("name asc,id asc")->select();
        
        $result=self::formataccess($rs,0);
        if($menu===0){
            return $result;
        }else{
            $arr=array();
            foreach ($result as $vf){
                foreach ($vf["list"] as $vk=>$vr){
                    $arr[]=$vr;
                }
            }
            return $arr;
        }
        
    }
    //权限列表&左侧菜单 递归 测试
    function formataccess($data, $slash, $pId=""){
        $tree = '';
        foreach($data as $k => $v){
            if(substr_count($v["name"],"/")===$slash){
                switch ($slash){
                    case 0:
                        $n=$v["name"];
                        break;
                    case 1:
                        $n=substr($v["name"],0,strpos($v["name"],"/"));
                        break;
                    case 2:
                        $n=substr($v["name"],0,strrpos($v["name"],"/"));
                        break;
                    default:
                        $n="";
                }
                if($n===$pId || $slash===0){
                    $v['list'] = self::formataccess($data, $slash+1,$v["name"]);
                    $tree[] = $v;
                }  
            }
        }
        return $tree;
    }
    
    //添加权限规则
    function addpermission(){
        if(request()->isAjax()){
            $res=array();
            $data=array(
                "id"=>input("id"),
                "title"=>input("title"),
                "name"=>strtolower(input("name")),
                "status"=>input("status"),
                "menu"=>input("menu"),
                "icon"=>input("icon"),
                "condition"=>input("condition"),
            );
            if(!preg_match("/^[A-Za-z0-9\/_]+$/", $data["name"]) || substr($data["name"],0,1)=="/" || substr($data["name"],strlen($data["name"])-1)=="/"){
                $res["error"]="sorry 权限的书写规则不正确 ".$data["name"];
            }else{
                if($data["id"]){
                    if(db("auth_rule")->update($data)){
                        $res["error"]="success";
                    }else{
                        $res["error"]="sorry 权限编辑失败";
                    }
                }else{
                    if(db("auth_rule")->insert($data)){
                        $res["error"]="success";
                    }else{
                        $res["error"]="sorry 权限添加失败";
                    }
                }
            }
            return json($res);
        }else{
            $id=input("id");
            if($id){
                //读取该权限
                $this->assign("rule",db("auth_rule")->find($id));
                return view();
            }else{
                return view();
            }
            
        }
        
    }
    
    //删除权限
    function delpermission(){
        if(request()->isAjax()){
            $res=array();
            $id=input("id",0);
            if(db("auth_rule")->where("id=".$id)->delete()){
                $res["error"]="success";
            }else{
                $res["error"]="权限删除失败";
            }
            return json($res);
        }
    }
    //删除权限ALL
    function delpermissionAll(){
        if(request()->isAjax()){
            $res=array();
            $id=input("id/a");
            foreach ($id as $v){
                db("auth_rule")->where("id=".$v["id"])->delete();
            }
            $res["error"]="success";
            return json($res);
        }
    }
    
    //公共方法
    private function myrolelist(){
        return db("auth_group")->order("id asc")->select();
    }
    
}

















?>